package com.emergency.flyinfo;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import com.emergency.service.RoadNetWebService;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class FlyReport extends Activity {
	private static final String TAG = "DataLineActivity";
	boolean clearThread=false;
	//private Handler handler;
	private Timer timer = new Timer();
	private TimerTask task;
	ProgressDialog pd;
	boolean showprograss=true;
	
	 public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.fly_report_layout);
	        ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	        pd = ProgressDialog.show(this, "数据加载中...", "正在加载数据,请稍候...", true,false);
	        /*final TextView txtViewRegister = (TextView)findViewById(R.id.delayfly);
	        txtViewRegister.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);  
	        txtViewRegister.setTextColor(Color.BLUE);
	        txtViewRegister.setOnClickListener(new OnClickListener() {
	        
				@Override
				public void onClick(View v) {
					txtViewRegister.setBackgroundColor(Color.YELLOW);
					new AlertDialog.Builder(FlyReport.this)
					// 以对话框形式通知用户选择的列表内容
					.setTitle("延误航班:" + "4架次")
					.setMessage("航班号"+"            "+"计划时间"+"        "+"出发/目的"+"       "+"延误时间"+"       "+"到离港"+"       "+"\n"
							+"GS6573"+"       "+"05-14 00:30"+"       "+"北京"+"               "+"1小时"+"              "+"到港"+ "\n"
							+ "GS6973"+"       "+"05-14 02:30"+"       "+"宜昌"+"               "+"2小时"+"              "+"离港" 
					+ "\n" + "GS8574"+"       "+"05-14 03:30"+"       "+"南昌"+"               "+"40分钟"+"            "+"到港"+
						"\n" + "GT6873"+"       "+"05-14 08:30"+"       "+"上海"+"               "+"3小时"+"              "+"离港")
					.setNegativeButton("关闭",  new DialogInterface.OnClickListener(){

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							txtViewRegister.setBackgroundColor(Color.WHITE);
						}
						
					}).show();
					
				}
			});
	        
	        final TextView txtViewRegister2 = (TextView)findViewById(R.id.cancelfly);
	        txtViewRegister2.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);  
	        txtViewRegister2.setTextColor(Color.BLUE);
	        txtViewRegister2.setOnClickListener(new OnClickListener() {
	        
				@Override
				public void onClick(View v) {
					txtViewRegister2.setBackgroundColor(Color.YELLOW);
					new AlertDialog.Builder(FlyReport.this)
					// 以对话框形式通知用户选择的列表内容
					.setTitle("取消航班:" + "4架次")
					.setMessage("航班号"+"            "+"计划时间"+"           "+"取消时间"+"          "+"出发/目的"+"          "+"到离港"+"       "+"\n"
							+"GS6573"+"       "+"05-14 00:30"+"       "+"05-14 01:30"+"             "+"北京"+"              "+"到港"+ "\n"
							+ "GS6973"+"       "+"05-14 02:30"+"       "+"05-14 03:30"+"             "+"上海"+"              "+"离港" 
					+ "\n" + "GS8574"+"       "+"05-14 03:30"+"       "+"05-14 04:30"+"             "+"平凉"+"             "+"到港"+
						"\n" + "GT6873"+"       "+"05-14 08:30"+"       "+"05-14 09:30"+"             "+"大连"+"              "+"离港")
					.setNegativeButton("关闭",  new DialogInterface.OnClickListener(){

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							txtViewRegister2.setBackgroundColor(Color.WHITE);
						}
						
					}).show();
					
				}
			});*/
	       
			NetworkInfo info = cwjManager.getActiveNetworkInfo();
			if (info != null && info.isAvailable()) {// 判断当前设备是否可以联网
				
					
					 new Thread(){
					    	
					    	public void run(){
					    		
						    	 
					    		if(isConnByHttp()){
						    			task = new TimerTask() {
											@Override
											public void run() {
												
												FlyReportString=RoadNetWebService.getFlyReportString("getAirportDetail","");
												//System.out.println("FlyReportString:"+FlyReportString);
												Message message = new Message();
												message.what = 0;
												handler.sendMessage(message);
											}
										};

										timer.schedule(task, 500, 300000);

										
					    		}else{
									
									CannotConnectServ();//这个方法写在了子县城里
									Message message = new Message();
									message.what = 2;
									handler.sendMessage(message);
									
								}
					    	}
						     
					      }.start();
				
			}else{
				
				CannotConnectNet();
				Message message = new Message();
				message.what = 3;
				handler.sendMessage(message);
			}
	     
	       
	    }
	 
	 private Handler handler=new Handler(){
		 @Override
			// 当有消息发送出来的时候就执行Handler的这个方法
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				// 处理UI
				switch (msg.what) {
				case 0:
					handler.post(ReportLinesUI);
					
					break;
				
				case 2:
					builder.create().show();
					break;
				case 3:
					builder2.create().show();
					break;
				}

			}
	 };
	 AlertDialog.Builder builder2;
	 public void CannotConnectNet() {// 当服务器连接不上的时候 就提示用户 并关闭主程序。

		 	builder2= new AlertDialog.Builder(
					FlyReport.this);
			builder2.setTitle("错误");
			builder2.setMessage("无法连接互联网，请稍候重试");
			builder2.setCancelable(false); // 禁止取消键
			builder2.setNegativeButton("确认", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			

		}
	 
	 AlertDialog.Builder builder;
	 public void CannotConnectServ() {

			builder = new AlertDialog.Builder(
					FlyReport.this);
			builder.setTitle("错误");
			builder.setMessage("无法连接服务器，请稍候重试");
			builder.setCancelable(false); // 禁止取消键
			builder.setNegativeButton("确认", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					pd.dismiss();
				}
			});
			
		}
	 public boolean isConnByHttp(){
	        boolean isConn = false;
	        URL url;
	        HttpURLConnection conn = null;
	        try {
	        	//交通委网
	        	//url=new URL("http://172.24.186.187:8887/phone/webService");
	        	//外网
	        	 //url=new URL("http://114.251.193.190:8899/phone");
	        	//内网
	        	// url = new URL("http://172.18.18.203:8199/phone/");
	        	url = new URL("http://172.28.18.2:7777/phone/");
	            conn = (HttpURLConnection)url.openConnection();
	            conn.setConnectTimeout(1000*6); 
	            if(conn.getResponseCode()==200){
	                isConn = true;
	            }
	            
	        } catch (MalformedURLException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }catch (IOException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }finally{
	            conn.disconnect();
	        }
	        return isConn;
	    }
	 
	 @Override
		protected void onStart() {
			super.onStart();
			Log.e(TAG, "start onStart~~~");
		}

		@Override
		protected void onRestart() {
			super.onRestart();
			Log.e(TAG, "start onRestart~~~");
			
		}

		@Override
		protected void onResume() {
			super.onResume();
			Log.e(TAG, "start onResume~~~");
		}

		@Override
		protected void onPause() {
			super.onPause();
			Log.e(TAG, "start onPause~~~");
			
			
		}

		@Override
		protected void onStop() {
			
			super.onStop();
			if(builder!=null){
				
				builder.create().dismiss();
			}
			pd.cancel();
			
			Log.e(TAG, "start onStop~~~");
			
		}

		@Override
		protected void onDestroy() {
			super.onDestroy();
			timer.cancel();
			
			finish();
			Log.e(TAG, "start onDestroy~~~");
		}
		
		
		// 构建Runnable对象，在runnable中更新界面
		Runnable ReportLinesUI = new Runnable() {
			@Override
			public void run() {
				
					initLines();
					pd.dismiss();
			}

		};
		
	    	String FlyReportString=null;
	    	List<String> xAxesString=new ArrayList<String>();
	 protected void initLines(){
		/* System.out.println("---------报表信息-------------");*/
		  
		   if(FlyReportString==null){//如果网络不通顺 则提示无法获取航班报表信息
	        	
	        	Toast toast = Toast.makeText(getApplicationContext(),
	        		     "由于网络问题，无法获取航班报表信息!", Toast.LENGTH_LONG);
	        		   toast.setGravity(Gravity.CENTER, 0, 0);
	        		   toast.show();

	        }else{
	        	
	        	
	        	   //每条曲线的名称
		        String[] titles = new String[]{"到港航班","离港航班"};
		        String[] SingleValue=FlyReportString.split(";");
		        List<double[]> x = new ArrayList<double[]>(); //点集的x坐标 
		        List<double[]> y = new ArrayList<double[]>(); //点集的y坐标
		        
		        double[] inPortValueX = new double[SingleValue.length];
		        double[] outPortValueX =new double[SingleValue.length];
		        double[] inPortValueY = new double[SingleValue.length];
		        double[] outPortValueY = new double[SingleValue.length];
		        xAxesString.clear();
		        for(int i=0;i<SingleValue.length;i++){
		        	String[] perValue=SingleValue[i].split(",");
		        	inPortValueX[i]=i;
		            outPortValueX[i]=i;
		        		
		        		xAxesString.add(perValue[0].toString());
		        		inPortValueY[i]=new Double(perValue[1].toString());
		        		outPortValueY[i]=new Double(perValue[2].toString());
		        	
		        }
		       
		        
		       x.add(inPortValueX);
		       x.add(outPortValueX);
		       y.add(inPortValueY);
		       y.add(outPortValueY);
		       
		      /*  x.add(new double[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21});
		        y.add(new double[]{23,14,5,30,20,25,23,44,11,55,32,11,77,33,88,12,33,54,18,9,21,15});
		        x.add(new double[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23});
		        y.add(new double[]{18,9,21,15,10,6,12,12,33,1,55,56,44,12,55,11,33,12,23,14,5,30,20,25});*/
		       /* x.add(new double[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35});
		        y.add(new double[]{18,9,21,15,10,6,12,12,33,1,55,56,144,12,55,311,233,112,23,14,5,30,20,25,23,44,11,55,32,11,77,33,88,12,33,54,18,9});*/
		        //保存点集数据 ，包括每条曲线的X，Y坐标
		        XYMultipleSeriesDataset dataset = buildDatset(titles,x,y);
		        int[] colors = new int[] {Color.RED,Color.BLUE};//每条曲线的颜色
		        //每条曲线点的形状
		        PointStyle[] styles = new PointStyle[]{PointStyle.CIRCLE, PointStyle.DIAMOND};
		        //曲线图的格式，包括颜色，值的范围，点和线的形状等等 
		        XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles, true);
		        
		        setChartSettings(renderer, "到离港航班(架次)", "时间", "架次", 0, 48, 0, 1000, Color.BLACK, Color.BLACK);
		        View chart = ChartFactory.getTimeChartView(this, dataset, renderer, "HH:mm");
		        
		       // setContentView(chart); 
		      // setContentView(R.layout.main);
		        LinearLayout layout = (LinearLayout)findViewById(R.id.dataline1);
		        layout.removeAllViews();   //先remove再add可以实现统计图更新
		        layout.addView(chart, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
	        }
		
	 }
	
		protected void setChartSettings(XYMultipleSeriesRenderer renderer,
				String title, String xTitle, String yTitle, double xMin,
				double xMax, double yMin, double yMax, int axesColor,
				int labelsColor) {
			renderer.setChartTitleTextSize(20);
			renderer.setChartTitle(title);
			renderer.setXTitle(xTitle);
			renderer.setYTitle(yTitle);
			renderer.setXAxisMin(xMin);
			renderer.setMarginsColor(Color.parseColor("#a6d8ff"));
			renderer.setDisplayValues(true);
			renderer.setXAxisMax(xMax);
			renderer.setYAxisMin(yMin);
			renderer.setYAxisMax(yMax);
			renderer.setPanEnabled(true, false);//设置Y轴不可拖动 X轴可以拖动
			renderer.setPanLimits(new double[]{0,50,0,1000});//设置拖动范围 X最小为0最大为50Y最小为0最大为1000
			renderer.setShowGrid(true);//显示网格线
			renderer.setGridColor(Color.BLACK);
			renderer.setAxisTitleTextSize(20);
			//renderer.setApplyBackgroundColor(true);
			//renderer.setBackgroundColor(Color.GRAY);
			renderer.setLegendTextSize(20);
			renderer.setXLabelsAngle(-15); // 设置 X 轴标签倾斜角度 (clockwise degree)
			renderer.setDisplayChartValues(true) ;//显示折线点上的数据
			renderer.setXLabels(0); // 设置X轴不显示数字（改用我们手动添加的文字标签）
			renderer.setAxesColor(axesColor);//设置轴的颜色
			renderer.setXLabelsColor(labelsColor);//设置X轴的字体颜色
			renderer.setYLabelsColor(0, Color.BLACK);//设置Y轴的字体颜色
			renderer.setLabelsColor(labelsColor);
			renderer.setZoomEnabled(true, false);//设置X轴可以缩放 Y轴不允许缩放
			renderer.setLabelsTextSize(20);
			/*for(int i=0;i<xAxesString.size();i++){
				
					renderer.addTextLabel(i, xAxesString.get(i));
				
				
			}*/
			for(int i=0;i<xAxesString.size();i++){
		        	if(i%2==0){
		        		
		        		 renderer.addTextLabel(i, xAxesString.get(i));
		        	}
	        	
	        }
		}

		private XYMultipleSeriesRenderer buildRenderer(int[] colors,
				PointStyle[] styles, boolean fill) {
			//曲线图的格式，包括颜色，值的范围，点和线的形状等等 
			XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer(); 
	        int length = colors.length; 
	        for (int i = 0; i < length; i++) 
	        { 
	            XYSeriesRenderer r = new XYSeriesRenderer(); 
	            r.setColor(colors[i]); 
	            r.setChartValuesTextSize(18);
	            r.setChartValuesTextAlign(Align.CENTER);
	            r.setPointStyle(styles[i]); 
	            r.setFillPoints(fill); 
	            renderer.addSeriesRenderer(r); 
	        } 
	       
	        return renderer; 
		}

		private XYMultipleSeriesDataset buildDatset(String[] titles, List xValues,
				List yValues) {
			// 用于数据的存放
			XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();

			int length = titles.length; // 有几条线
			for (int i = 0; i < length; i++) {
				//XYseries对象,用于提供绘制的点集合的数据
				XYSeries series = new XYSeries(titles[i]); // 根据每条线的名称创建
				double[] xV = (double[]) xValues.get(i); // 获取第i条线的数据
				double[] yV = (double[]) yValues.get(i);
				int seriesLength = xV.length; // 有几个点

				for (int k = 0; k < seriesLength; k++) // 每条线里有几个点
				{
					series.add(xV[k], yV[k]);
				}

				dataset.addSeries(series);
			}

			return dataset;
		}
	 
	
}
